package com.yzj.musicplayer.slice;

import com.yzj.musicplayer.Player.PlayerManager;
import com.yzj.musicplayer.Player.StateListener;
import com.yzj.musicplayer.Provider.CommonProvider;
import com.yzj.musicplayer.Provider.ViewProvider;
import com.yzj.musicplayer.ResourceTable;
import com.yzj.musicplayer.util.Log;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.ability.IAbilityContinuation;
import ohos.aafwk.ability.continuation.*;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.IntentParams;
import ohos.agp.animation.Animator;
import ohos.agp.animation.AnimatorProperty;
import ohos.agp.components.*;
import ohos.agp.components.element.*;
import ohos.agp.window.dialog.CommonDialog;
import ohos.distributedschedule.interwork.DeviceInfo;
import ohos.distributedschedule.interwork.DeviceManager;
import ohos.global.resource.NotExistException;
import ohos.global.resource.Resource;
import ohos.hiviewdfx.HiLog;
import ohos.multimodalinput.event.SpeechEvent;

import java.io.IOException;
import java.lang.ref.WeakReference;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

public class MainAbilitySlice extends AbilitySlice implements StateListener, IAbilityContinuation, IContinuationRegisterManager {

    private static final String TAG = "=>"+MainAbilitySlice.class.getSimpleName();

    /*            定义一些“键” 用于发送键值对信息             */
    //当前时间
    private static final String KEY_CURRENT_TIME = "main_ability_slice_current_time";
    //当前的进度
    private static final String KEY_POSITION = "main_ability_slice_position";
    //当前的播放状态
    private static final String KEY_PLAY_STATE = "main_ability_slice_play_state";

    private static final String KEY_Flag = "main_ability_slice_play_flag";
    /*            定义一些“键” 用于发送键值对信息             */

    /*          歌曲路径         */
    private static final String URI1 = "resources/rawfile/yourname.wav";

    private static final String URI2 = "resources/rawfile/jojo.wav";

    private final String[] musics = {URI1, URI2};
    /*          歌曲路径         */

    /* 歌曲海报 */
    private final int[] posters = {ResourceTable.Media_yourname, ResourceTable.Media_jojo};
    /* 歌曲背景 */
    private final int[] bgposters = {ResourceTable.Media_playerbg, ResourceTable.Media_playerbg2};
    /* 歌曲名字 */
    private  final String[] mName = {"前前前世","il vento d'oro"};
    /* 播放器 */
    private PlayerManager playerManager;
    /* 属性动画 */
    private AnimatorProperty animatorProperty;
    /* 整个布局对象 */
    private DirectionalLayout dl;
    /* 歌曲文本组件 */
    private Text musicNameText;
    /* 当前时间文本组件 */
    private Text currentTimeText;
    /* 总时间文本组件 */
    private Text totalTimeText;
    /* 进度条组件 */
    private Slider slider;
    /* 播放按钮组件 */
    private Image musicPlayButton;
    /*前一首*/
    private Image playnextButton;
    /*下一首*/
    private Image playpreButton;
    /* 歌曲海报图片组件 */
    private Image musicPosters;
    /* 流转按钮组件 */
    private Image remotePlay;
    /* 当前位置 */
    private int currentPos = 0;
    /* 当前播放歌曲路径 */
    private String currentUri;

    //是否是互动播放，true表示远端迁移恢复的
    private boolean isInteractionPlay;

    /*  当前时间  */
    private int currentTime;
    /*  总时间  */
    private int totalTime;
    /* 当前是否在播放 */
    private boolean isPlaying;

    private int flag=0;

    List<ohos.distributedhardware.devicemanager.DeviceInfo> onlineDevices;
    // 设备列表按最近使用排序
    int MOST_RECENTLY_USED = 0;
    // 获取设备管理类
    ohos.distributedhardware.devicemanager.DeviceManager devManager;

    //定义ListContainer
    private ListContainer deviceListContainer;
    private final List<DeviceInfo> devices = new ArrayList<>(0);
    //弹框
    private CommonDialog devicesDialog;

    //测试
    //播放
    private Component.VoiceEvent eventplay;
    //暂停
    private Component.VoiceEvent eventpause;
    //下一首
    private Component.VoiceEvent eventnext;
    //前一首
    private Component.VoiceEvent eventpre;
    //流转
    private Component.VoiceEvent eventremote;

    /*弹窗*/
    private int abilityToken;
    private String selectDeviceId ;

    private boolean isReversibly = false;
    private IContinuationRegisterManager continuationRegisterManager;
    // 设置流转任务管理服务设备状态变更的回调
    private IContinuationDeviceCallback callback = new IContinuationDeviceCallback() {
        @Override
        public void onConnected(ContinuationDeviceInfo deviceInfo) {
            // 在用户选择设备后设置设备ID
            selectDeviceId = deviceInfo.getDeviceId();
            continueAbility(selectDeviceId);
            //更新选择设备后的流转状态
            continuationRegisterManager.updateConnectStatus(abilityToken, selectDeviceId, DeviceConnectState.CONNECTED.getState(), null);
        }

        @Override
        public void onDeviceConnectDone(String s, String s1) {

        }

        @Override
        public void onDeviceDisconnectDone(String s) {

        }

        @Override
        public void onDisconnected(String deviceId) {
        }
    };
    // 设置注册流转任务管理服务回调
    private RequestCallback requestCallback = new RequestCallback() {
        @Override
        public void onResult(int result) {
            abilityToken = result;
        }
    };
    // 显示设备列表，获取设备信息
    private Component.ClickedListener mShowDeviceListListener = new Component.ClickedListener() {
        @Override
        public void onClick(Component arg0) {
            // 设置过滤设备类型
            ExtraParams params = new ExtraParams();
            String[] devTypes = new String[]{ExtraParams.DEVICETYPE_SMART_PAD, ExtraParams.DEVICETYPE_SMART_PHONE};
            params.setDevType(devTypes);
            String jsonParams = "{'filter':{'commonFilter':{'system':{'harmonyVersion':'2.0.0'},'groupType':'1|256','curComType': 0x00030004,'faFilter':'{\"localVersionCode\":1,\"localMinCompatibleVersionCode\":2,\"targetBundleName\": \"com.xxx.yyy\"}'}},'transferScene':0,'remoteAuthenticationDescription': '拉起HiVision扫描弹框描述','remoteAuthenticationPicture':''}";
            params.setJsonParams(jsonParams);

            // 显示选择设备列表
            continuationRegisterManager.showDeviceList(abilityToken, null, null);

        }
    };
    private Component.SpeechEventListener speech_mShowDeviceListListener = new Component.SpeechEventListener() {
        @Override
        public boolean onSpeechEvent(Component component, SpeechEvent speechEvent) {
            if(speechEvent.getActionProperty().equals("流转")){
                // 显示选择设备列表
                continuationRegisterManager.showDeviceList(abilityToken, null, null);
            }
            return false;
        }
    };
    //onStart()方法
    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);
        // 调用DeviceManager的getTrustedDeviceList接口获取在线设备列表
        continuationRegisterManager = getContinuationRegisterManager();
        mRegister();
      //  initDevicesDialog();
        initView();
        initMedia();
        updateUI();

    }
    /**
     * 初始化界面组件，实现对应按钮的监听事件
     * 播放或暂停、上一首、下一首、迁移以及进度条的进度变化事件的监听
     */
    void mRegister(){
        //增加过滤条件
        ExtraParams params = new ExtraParams();
        String[] devTypes = new String[]{ExtraParams.DEVICETYPE_SMART_PAD, ExtraParams.DEVICETYPE_SMART_PHONE};
        params.setDevType(devTypes);
        String jsonParams = "{'filter':{'commonFilter':{'system':{'harmonyVersion':'2.0.0'},'groupType':'1|256','curComType': 0x00030004,'faFilter':'{\"localVersionCode\":1,\"localMinCompatibleVersionCode\":2,\"targetBundleName\": \"com.xxx.yyy\"}'}},'transferScene':0,'remoteAuthenticationDescription': '拉起HiVision扫描弹框描述','remoteAuthenticationPicture':''}";
        params.setJsonParams(jsonParams);
        continuationRegisterManager.register(getBundleName(), params, callback, requestCallback);
    }
    void initView(){
        //绑定热词

        eventplay = new Component.VoiceEvent("播放");
        eventpause = new Component.VoiceEvent("暂停");
        eventnext = new Component.VoiceEvent("下一首");
        eventpre = new Component.VoiceEvent("上一首");
        eventremote = new Component.VoiceEvent("流转");

        //初始化音乐名称
        musicNameText = (Text) findComponentById(ResourceTable.Id_musicName);
        //初始化进度条时间
        currentTimeText = (Text) findComponentById(ResourceTable.Id_playProgressTime);
        //初始化音乐总时间
        totalTimeText = (Text) findComponentById(ResourceTable.Id_playTotalTime);
        //初始化音乐海报
        musicPosters = (Image) findComponentById(ResourceTable.Id_musicPoster);
        //初始化播放按钮
        musicPlayButton = (Image) findComponentById(ResourceTable.Id_playBtn);
        //初始化跳转按钮
        remotePlay = (Image) findComponentById(ResourceTable.Id_playRemote);
        //初始化上一首按钮
        playpreButton=findComponentById(ResourceTable.Id_playPreBtn);
        playpreButton.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                prevMusic(component);
            }
        });
        //初始化下一首按钮
        playnextButton=findComponentById(ResourceTable.Id_playNextBtn);
        playnextButton.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                nextMusic(component);
            }
        });
        //为播放按钮添加点击监听
        musicPlayButton.setClickedListener(this::playOrPauseMusic);
        //初始化整个局部对象
        dl = findComponentById(ResourceTable.Id_dl);
        //初始化属性动画对象
        animatorProperty = musicPosters.createAnimatorProperty();
        animatorProperty.setCurveType(Animator.CurveType.LINEAR);
        //初始化进度条
        slider = (Slider) findComponentById(ResourceTable.Id_playProgressBar);
        //为进度条添加值变化监听
        slider.setValueChangedListener(new ValueChangedListenerImpl());
        //为流转按钮添加点击监听
//       remotePlay.setClickedListener(new Component.ClickedListener() {
//           @Override
//           public void onClick(Component component) {
//               continueAbility(component);
//           }
//        });
        Button b = new Button(getContext());

        Component component =new Component(getContext());
        component.subscribeVoiceEvents(eventplay);
        component.setSpeechEventListener(new Component.SpeechEventListener() {
            @Override
            public boolean onSpeechEvent(Component component, SpeechEvent speechEvent) {
                playOrPause();
           Log.info(TAG,"响应");
                return true;
            }
        });
        //注册热词
        musicPlayButton.subscribeVoiceEvents(eventplay);
        musicPlayButton.subscribeVoiceEvents(eventpause);
        musicPlayButton.setSpeechEventListener(new Component.SpeechEventListener() {
            @Override
            public boolean onSpeechEvent(Component component, SpeechEvent speechEvent) {
                if(speechEvent.getActionProperty().equals("播放")){
                    if(playerManager.isPlaying()){
                        Log.info(TAG,"正在播放");
                    }
                    else{
                        playOrPause();
                    }
                    return true;

                }
                else if(speechEvent.getActionProperty().equals("暂停")){
                    if(!playerManager.isPlaying()){
                        Log.info(TAG,"已经暂停了");

                    }
                    else{
                        playOrPause();
                    }
                    return true;
                }
                return false;
            };
        });
        playnextButton.subscribeVoiceEvents(eventnext);
        playnextButton.setSpeechEventListener(new Component.SpeechEventListener() {
            @Override
            public boolean onSpeechEvent(Component component, SpeechEvent speechEvent) {
                if(speechEvent.getActionProperty().equals("下一首")){
                    nextMusic(component);
                    return true;
                }
                return false;
            }
        });
        playpreButton.subscribeVoiceEvents(eventpre);
        playpreButton.setSpeechEventListener(new Component.SpeechEventListener() {
            @Override
            public boolean onSpeechEvent(Component component, SpeechEvent speechEvent) {
                if(speechEvent.getActionProperty().equals("上一首")){
                    prevMusic(component);
                    return  true;
                }
                return false;
            }
        });
        remotePlay.setClickedListener(mShowDeviceListListener);
        remotePlay.setClickedListener(mShowDeviceListListener);
        remotePlay.subscribeVoiceEvents(eventplay);
        remotePlay.setSpeechEventListener(speech_mShowDeviceListListener);

//
//        remotePlay.setClickedListener(new Component.ClickedListener() {
//            @Override
//            public void onClick(Component component) {
//                initDevices();
//                showDeviceList();
//            }
//        });
//
//        deviceListContainer.setItemClickedListener(new ListContainer.ItemClickedListener() {
//            @Override
//            public void onItemClicked(ListContainer listContainer, Component component, int i, long l) {
//                scheduleRemoteAbility(new ISelectResult() {
//                    @Override
//                    public void onSelectResult(String deviceId) {
//
//                        continueAbility(deviceId);
//                    }
//                },i);
//            }
//        });
    }

    /**
     * 初始化媒体对象
     * 当前播放歌曲资源
     * 播放器管理者
     */
    private void initMedia() {
        Log.debug(TAG, "initMedia");
        //当前媒体URI
        currentUri = musics[currentPos];
        Log.debug(TAG, "initMedia,currentUri:"+currentUri);
        //初始化playerManager 传入当前页面，歌曲路径
        playerManager = new PlayerManager(getApplicationContext(), currentUri);
        //弱引用对象，不会阻止它们的引用对象被终结、终结和回收。 弱引用最常用于实现规范化映射。
        WeakReference<StateListener> playerStateListener = new WeakReference<>(this);
        //设置状态监听器
        playerManager.setPlayerStateListener(playerStateListener.get());
        //初始化播放器信息
        playerManager.prepareMusic();
        Log.debug(TAG, "initMedia FINISH");
    }


    /**
     * 远端迁移后恢复的播放，恢复播放器的播放进度
     * 更新UI界面
     */
    private void updateUI() {
        Log.debug(TAG, "updateUI");
        //设置海报
        musicPosters.setPixelMap(posters[currentPos]);
        try {

            Resource resource = getResourceManager().getResource(bgposters[currentPos]);

            PixelMapElement pixelMapElement = new PixelMapElement(resource);
            if(flag == 0)
            {

            }
            else{
            dl.setBackground(pixelMapElement);
            flag =0;
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NotExistException e) {
            e.printStackTrace();
        }

        //当前时间和总时长
        currentTimeText.setText(getTime(currentTime));
        totalTimeText.setText(getTime(playerManager.getTotalTime()));
        //播放进度
        slider.setMaxValue(playerManager.getTotalTime());
        slider.setProgressValue(currentTime);
        //总时长
        totalTime=playerManager.getTotalTime();

        //远端迁移恢复
        if (isInteractionPlay) {
            Log.debug(TAG, "remotePlay，rewindTo："+currentTime);
            playerManager.rewindTo(currentTime);
            if (!isPlaying) {
                return;
            }
            //播放
            playerManager.play();
        }
    }

    private void continueAbility(Component component) {
        try {
            continueAbility();
        } catch (IllegalStateException e) {
            Log.info(TAG, e.getMessage());
        }
    }


    /**
     * 上一首
     * @param component
     */
    private void prevMusic(Component component) {
        flag = 1;
        currentPos = currentPos == 0 ? 1 : 0;
        currentUri = musics[currentPos];
        //
        playerManager.switchMusic(currentUri);
        //总时长
        totalTime=playerManager.getTotalTime();
        animatorProperty.reset();

    }


    /**
     * 下一首
     * @param component
     */
    private void nextMusic(Component component) {
        flag = 1;
        currentPos = currentPos == 0 ? 1 : 0;
        currentUri = musics[currentPos];
        //切换音乐
        playerManager.switchMusic(currentUri);
        //总时长
        totalTime=playerManager.getTotalTime();
        animatorProperty.reset();
    }

    /**
     * 播放或暂停音乐
     * @param component
     */
    private void playOrPauseMusic(Component component) {
        //
        playOrPause();
    }

    /**
     * 播放或暂停
     */
    private void playOrPause() {

        Log.debug(TAG, "playOrPause,playerManager:"+playerManager);
        try {
            //
            if (playerManager.isPlaying()) {
                Log.debug(TAG, "playOrPause pause");
                playerManager.pause();
            }else{
                //设置资源
                playerManager.setResource(currentUri);
                //设置进度
                playerManager.rewindTo(currentTime);
                playerManager.play();
                Log.debug(TAG, "playOrPause play");
            }
        } catch (Exception e) {
            Log.error(TAG, "playOrPause");
            e.printStackTrace();
        }
    }
    @Override
    protected void onInactive() {
        super.onInactive();
        //
        playerManager.pause();
    }
    @Override
    protected void onStop() {
        super.onStop();
        //
        playerManager.releasePlayer();
    }
    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    /*  ------StateListener接口的方法重写------  */

    /*
    *  播放成功的话
    * */
    @Override
    public void onPlaySuccess(int totalTime) {
        //设置图标
        musicPlayButton.setPixelMap(ResourceTable.Media_pause);
        //设置总时长文本
        this.totalTimeText.setText(getTime(totalTime));
        //设置进度条
        slider.setMaxValue(totalTime);
        //设置当前歌曲海报
        musicPosters.setPixelMap(posters[currentPos]);

        try {

            Resource resource = getResourceManager().getResource(bgposters[currentPos]);

            PixelMapElement pixelMapElement = new PixelMapElement(resource);
            if(flag == 0)
            {

            }
            else{
                dl.setBackground(pixelMapElement);
                flag = 0;
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NotExistException e) {
            e.printStackTrace();
        }


        animatorProperty.rotate(360+musicPosters.getRotation()).setDuration(100000).setLoopedCount(-1).start();


    }

    /*
    * 暂停成功的话
    * */
    @Override
    public void onPauseSuccess() {
        //设置图标
        musicPlayButton.setPixelMap(ResourceTable.Media_play);
        animatorProperty.stop();
    }

    /*
    * 拖动进度条的话
    * */
    @Override
    public void onPositionChange(int currentTime) {
        if(currentTime < totalTime){
            Log.info(TAG, "onPositionChange currentTime = " + currentTime+",totalTime="+totalTime);
            this.currentTime = currentTime;
            //设置播放时间文本
            this.currentTimeText.setText(getTime(currentTime));
            //设置进度条的当前播放时间
            slider.setProgressValue(currentTime);
        }else{
            Log.info(TAG, "onPositionChange, current song end");

            //设置播放器图标
            musicPlayButton.setPixelMap(ResourceTable.Media_play);
        }
    }
    /*
    * 当前音乐播放完毕的话
    * */
    @Override
    public void onMusicFinished() {
        currentPos = currentPos == 0 ? 1 : 0;
        currentUri = musics[currentPos];
        //切换歌曲
        playerManager.switchMusic(currentUri);
        //总时长
        totalTime=playerManager.getTotalTime();
    }


    /*
    * 设置歌曲名称
    * */
    @Override
    public void onUriSet(String name) {
        //设置歌曲名称
        musicNameText.setText(mName[currentPos]);
    }
    /*  ------StateListener接口的方法重写------  */


    /*  ------IAbilityContinuation接口方法重写------  */
    @Override
    public boolean onStartContinuation() {
        return true;
    }
    /*
    *  存储当前设备信息打包给目标设备
    * */
    @Override
    public boolean onSaveData(IntentParams intentParams) {
        intentParams.setParam(KEY_CURRENT_TIME, currentTime);
        intentParams.setParam(KEY_POSITION, currentPos);

        intentParams.setParam(KEY_PLAY_STATE, String.valueOf(playerManager.isPlaying()));

        intentParams.setParam(KEY_Flag,1);
        return true;
    }
   /*
   *   从目标设备流转回当前设备的时候解析目标设备的信息
   * */
    @Override
    public boolean onRestoreData(IntentParams intentParams) {
        if (!(intentParams.getParam(KEY_POSITION) instanceof Integer)) {
            return false;
        }
        if (!(intentParams.getParam(KEY_CURRENT_TIME) instanceof Integer)) {
            return false;
        }
        if (!(intentParams.getParam(KEY_PLAY_STATE) instanceof String)) {
            return false;
        }
        if (!(intentParams.getParam(KEY_Flag) instanceof Integer)) {
            return false;
        }

        //恢复数据，获取迁移过来的参数：播放位置、时间和播放状态
        currentPos = (int) intentParams.getParam(KEY_POSITION);
        currentTime = (int) intentParams.getParam(KEY_CURRENT_TIME);
        Object object = intentParams.getParam(KEY_PLAY_STATE);
        flag = (int)intentParams.getParam(KEY_Flag);


        if (object instanceof String) {
            isPlaying = Boolean.parseBoolean((String) object);
        }
        isInteractionPlay = true;
        Log.info(TAG, "onRestoreData:" + currentTime);
        return true;
    }
    /*
    *  完成流转的时候，结束当前设备页面
    * */
    @Override
    public void onCompleteContinuation(int i) {
        terminate();
    }

    @Override
    public void register(String s, ExtraParams extraParams, IContinuationDeviceCallback iContinuationDeviceCallback, RequestCallback requestCallback) {

    }

    @Override
    public void unregister(int i, RequestCallback requestCallback) {

    }

    @Override
    public void updateConnectStatus(int i, String s, int i1, RequestCallback requestCallback) {

    }

    @Override
    public void showDeviceList(int i, ExtraParams extraParams, RequestCallback requestCallback) {

    }

    @Override
    public void disconnect() {

    }
    /*  ------IAbilityContinuation接口方法重写------  */



    /**
     *   成员内部类 进度条值变化的监听事件类
     */
    private class ValueChangedListenerImpl implements Slider.ValueChangedListener {
        @Override
        public void onProgressUpdated(Slider slider, int progress, boolean fromUser) {
            //进度条更新
            currentTime = progress;
        }
        @Override
        public void onTouchStart(Slider slider) {
            Log.debug(TAG, "onTouchStart");
        }

        @Override
        public void onTouchEnd(Slider slider) {
            Log.debug(TAG, "onTouchEnd");
            //快速更改播放进度
            playerManager.rewindTo(currentTime);
            //当前播放时间
            currentTimeText.setText(getTime(currentTime));
        }
    }


    /**
     * 获取时间
     * @param time
     * @return
     */
    private String getTime(int time) {
        Date date = new Date(time);
        DateFormat dateFormat = new SimpleDateFormat("mm:ss");
        return dateFormat.format(date);
    }

        //查找组网内的设备


    private void initDevices() {
        if (devices.size() > 0) {
            devices.clear();
        }
        List<DeviceInfo> deviceInfos = DeviceManager.getDeviceList(DeviceInfo.FLAG_GET_ONLINE_DEVICE);
        devices.addAll(deviceInfos);
    }


    private void fineDevices(){

        Map<String, Object> filter = new HashMap<>();
        filter.put(ohos.distributedhardware.devicemanager.DeviceManager.TARGET_PACKAGE_NAME, getBundleName());
        filter.put(ohos.distributedhardware.devicemanager.DeviceManager.SORT_TYPE, 0);
        if (devManager ==null) {
            Log.info(TAG, "scheduleRemoteAbility devManager is null");
            return;
        }
        onlineDevices = devManager.getTrustedDeviceList(getBundleName(), filter);

    }

     //* 对设备列表ListContainer组件进行渲染

    private void showDeviceList() {
        CommonProvider<DeviceInfo> commonProvider = new CommonProvider<DeviceInfo>( devices, getContext(),
                ResourceTable.Layout_device_list) {
            @Override
            protected void convert(ViewProvider viewProvider, DeviceInfo item, int position) {
                viewProvider.setText(ResourceTable.Id_device_text, item.getDeviceName());
            }


        };

        deviceListContainer.setItemProvider(commonProvider);

        commonProvider.notifyDataChanged();
        devicesDialog.show();
    }


      //初始化设备列表弹框

    private void initDevicesDialog(){
        devicesDialog = new CommonDialog(this);

        Component dialogComponent = LayoutScatter.getInstance(getContext())
                .parse(ResourceTable.Layout_remote_devices, null, true);
        devicesDialog.setContentCustomComponent(dialogComponent);
        deviceListContainer = (ListContainer) dialogComponent.findComponentById(ResourceTable.Id_device_list_container);
    }

    private void scheduleRemoteAbility(ISelectResult listener,int ID) {
        // 判断组网设备是否为空
        if (devices.isEmpty()) {
            listener.onSelectResult(null);
            Log.info(TAG,"组网为空");
            return;
        }
        int numDevices = devices.size();
        List<String> deviceIds = new ArrayList<>(numDevices);
        devices.forEach((device) -> {
            deviceIds.add(device.getDeviceId());
        });
        // 以选择首个设备作为目标设备为例
        // 开发者也可按照具体场景，通过其它方式进行设备选择
        String selectedDeviceId = deviceIds.get(ID);
        listener.onSelectResult(selectedDeviceId);
    }
    // ISelectResult是一个自定义接口，用来处理指定设备deviceId后执行的行为
    interface ISelectResult {
        void onSelectResult(String deviceId);
    }

}
